package com.shuyun.classloader;

import cn.hutool.core.io.file.FileReader;

import java.io.File;

/**
 * @description:
 * @author: shuai.chen@shuyun.com
 * @date: 2021/8/23 1:31 下午
 */
public class CustomClassLoader extends ClassLoader {

    private String classPath;

    public CustomClassLoader(String classPath) {
        this.classPath = classPath;
    }

    /**
     * 重写loadClass方法，才能不走双亲委派
     * @param name
     * @param resolve
     * @return
     * @throws ClassNotFoundException
     */
    @Override
    protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
        Class<?> aClass = findClass(name);
        if (aClass != null) {
            return aClass;
        }
        return super.loadClass(name, resolve);
    }

    @Override
    protected Class<?> findClass(String name) {
        File file = new File(classPath);
        byte[] bytes = fileToByte(file);
        Class<?> clazz = this.defineClass(name, bytes, 0, bytes.length);
        return clazz;
    }

    /**
     *
     * @param file
     * @return
     */
    private byte[] fileToByte(File file) {
        FileReader fileReader = new FileReader(file);
        return fileReader.readBytes();
    }

}
